package com.bjzsly.star3.xyh.auth;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.bjzsly.star3.shareclick.utils.WeChatUtils;
import com.bjzsly.star3.xyh.MainActivity;
import com.bjzsly.star3.xyh.R;
import com.bjzsly.star3.xyh.auth.model.UserInfoWx;
import com.bjzsly.star3.xyh.auth.model.WxAccess;
import com.bjzsly.star3.xyh.auth.model.WxUserOpen;
import com.bjzsly.star3.xyh.manager.OnUserCallBack;
import com.bjzsly.star3.xyh.manager.UserUtils;
import com.bjzsly.star3.xyh.utils.DeviceUtil;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ly on 2017/9/21.
 * solve auth relate issues
 */

public class TxShareUtils {


    public static final String SCOPE_LOGIN_QQ = "loginQQ";
    public static final String SCOPE_GET_USER_INFO_QQ = "getUserInfoQQ";


    private Context mCtx;

    private static TxShareUtils shareUtils;

//    private String APPKEY_QQ = "101430931";
//    private String APPID_WX = "wxbf0cda00d886aec9";
//    private String APP_SECERT_WX = "15e557ba2e3e65d5f5f4744f97cc6c9e";
    private String APPKEY_QQ = "101445908";
//    private String APPID_WX = "wxa5d77cd210b4d02b";
//    private String APP_SECERT_WX = "1d2fb26dc9363fc9067ba14bf9aac9aa";
    private String APPID_WX = "wx30bd09b7b0561fbe";
    private String APP_SECERT_WX = "b9fbcd2fe9957133eb1b04c9f6c17e92";

    private Tencent mTencent;
    private IWXAPI mIwxapi;

    /**
     * QQ
     */

    private final int SHARE_TO_QQ_TYPE_TYPE_DEFAULT = 0;
    private final int SHARE_TO_QQ_TYPE_IMAGE_LOCAL = 2;
    private final int SHARE_TO_QQ_TYPE_IAMGE_NET = 3;
    private final int SHARE_TO_QQ_TYPE_APP = 4;


    private final int SHARE_TO_QZONE_TYPE_IMAGE_TEXT = 0;

    private int shareType = QQShare.SHARE_TO_QQ_TYPE_DEFAULT;


    /**
     * Wx
     */
    //图片尺寸过大时，微信不能分享
    private static final int THUMB_SIZE = 60;
    private int SCENE_SESSION = SendMessageToWX.Req.WXSceneSession;
    private int SCENE_TIMELINE = SendMessageToWX.Req.WXSceneTimeline;
    private int SCENE_FAVORITE = SendMessageToWX.Req.WXSceneFavorite;

    public static TxShareUtils getInstance() {
        if (shareUtils == null)
            shareUtils = new TxShareUtils();
        return shareUtils;
    }

    public static void initShare(Context ctx) {
        getInstance().init(ctx);
    }

    private TxShareUtils() {
    }

    public void init(Context ctx) {
        this.mCtx = ctx;
//        mTencent = Tencent.createInstance(APPKEY_QQ, ctx);
        mIwxapi = WXAPIFactory.createWXAPI(ctx, APPID_WX, true);
        mIwxapi.registerApp(APPID_WX);
    }

    public void recycle() {
        try {
            if (mIwxapi != null) {
                mIwxapi.unregisterApp();
                mIwxapi.detach();
            }
        } catch (Exception e) {
        }

    }

    private String curApppId = APPID_WX;

    public void recreateWxFactory(Context ctx, String Wx_AppId) {
        if (!TextUtils.isEmpty(curApppId) && !TextUtils.isEmpty(Wx_AppId) && curApppId.equals(Wx_AppId))
            return;
        curApppId = Wx_AppId;
        if (mIwxapi != null)
            mIwxapi.unregisterApp();
        mIwxapi = WXAPIFactory.createWXAPI(ctx, Wx_AppId, false);
        mIwxapi.registerApp(Wx_AppId);
    }


    /**
     * -----------------------------------    QQ相关        -------------------------------------------------
     */


    public void loginQQ(Activity act, IUiListener listener) {
//        Toast.makeText(act, mTencent.isSessionValid() + "", Toast.LENGTH_SHORT).show();
//        if (!mTencent.isSessionValid()) {
        mTencent.login(act, "all", listener);
//        }
    }

    public void getUserInfoQQ(Context ctx, IUiListener listener) {
        if (mTencent.isSessionValid() && mTencent.getQQToken().getOpenId() != null) {
            UserInfo mInfo = new UserInfo(ctx, mTencent.getQQToken());
            mInfo.getUserInfo(listener);
        }
    }


    public void shareQQ(Activity act, String title, String summary,  String imgUrl,String targetUrl) {
        Bundle bundle = new Bundle();
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
        bundle.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        bundle.putInt(QQShare.SHARE_TO_QQ_EXT_INT, 0x00);
        mTencent.shareToQQ(act, bundle,MainActivity.qqShareListener);
    };


//    public void shareQQZonePics(Activity act, ArrayList<String> imgUrls, BaseUIListener.OnUICallBack onUICallBack) {
//        Bundle params = new Bundle();
//        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
////        params.putStringArrayList(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imgUrls);
//        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imgUrls.get(0));
////        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, appName.getText().toString());
//        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
//        mTencent.shareToQzone(act, params, new BaseUIListener(act, SCOPE_LOGIN_QQ, onUICallBack));
//    }


    public void shareQzone(Activity act, String title, String summary, String imgUrl, String targetUrl) {
        shareQzone(act, title, summary, imgUrl, targetUrl);
    }


    private void shareQZone(Activity act, String title, String summary, String imgUrl, String targetUrl) {
        Bundle bundle = new Bundle();
        bundle.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl);

    }


    public static void onQQActivityResult(int requestCode, int resultCode, Intent data, IUiListener listener) {
        if (requestCode == Constants.REQUEST_LOGIN ||
                requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data, listener);
        }
    }


//    public void onQQShareActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == Constants.REQUEST_QZONE_SHARE) {
//            Tencent.onActivityResultData(requestCode, resultCode, data, qqShareListener);
//        } else if (requestCode == Constants.REQUEST_QQ_SHARE) {
//            Tencent.onActivityResultData(requestCode, resultCode, data, qqShareListener);
//        }
//    }



    public void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    public String getQQOpenId(JSONObject jsonObject) {
        try {
            initOpenidAndToken(jsonObject);
            return mTencent.getOpenId();
        } catch (Exception e) {
        }
        return null;
    }

    public String getQQOpenId() {
        return mTencent.getOpenId();
    }

    public static boolean isQQInstall(Context ctx){
        return DeviceUtil.isAppInstall(ctx,"com.tencent.mobileqq");
    }


    /**
     * -----------------------------------    WX相关        -------------------------------------------------
     */

    public boolean isWxInstall() {
        return mIwxapi.isWXAppInstalled();
    }


    public void loginWX() {
        if (mIwxapi.isWXAppInstalled()) {
            WeChatUtils.configType(mCtx, WeChatUtils.TYPE_WX_AUTH_LOGIN);
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wx_login";
            mIwxapi.sendReq(req);
        } else {
            Toast.makeText(mCtx, "请先安装微信", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * model WxUserOpen
     */
    public static void loginWx(String code, final OnAuthCallBack onAuthCallBack) {
        UserUtils.getWxAccessToken(code, new OnUserCallBack<WxAccess>() {
            @Override
            public void onSuccess(WxAccess wxAccess) {
                if (wxAccess != null) {
                    String refreshToken = wxAccess.getRefresh_token();
                    if (refreshToken != null) {
                        getWxRefreshOpenId(refreshToken, onAuthCallBack);
                    }
                }
            }

            @Override
            public void onFail(String msg) {
                if (onAuthCallBack != null)
                    onAuthCallBack.onFail("getAccessToken fail : " + msg);
            }
        });
    }

    private static void getWxRefreshOpenId(String refreshToken, final OnAuthCallBack onAuthCallBack) {
        UserUtils.getWxRefreshOpenId(refreshToken, new OnUserCallBack<WxUserOpen>() {
            @Override
            public void onSuccess(WxUserOpen wxUserOpen) {
                if (wxUserOpen != null) {
//                    String openId = wxUserOpen.getOpenid();
//                    if (openId != null) {
                    if (onAuthCallBack != null)
                        onAuthCallBack.onSuccess(wxUserOpen);
//                    }
                }
            }

            @Override
            public void onFail(String msg) {
                if (onAuthCallBack != null)
                    onAuthCallBack.onFail("getOpenId fail : " + msg);
            }
        });
    }

    /**
     * model UserInfoWx
     */
    public static void getWxUserInfo(String accessToken, String openId, final OnAuthCallBack onAuthCallBack) {
        UserUtils.getWxUserInfo(accessToken, openId, new OnUserCallBack<UserInfoWx>() {
            @Override
            public void onSuccess(UserInfoWx userInfoWx) {
                if (userInfoWx != null && onAuthCallBack != null)
                    onAuthCallBack.onSuccess(userInfoWx);
            }

            @Override
            public void onFail(String msg) {
                if (onAuthCallBack != null)
                    onAuthCallBack.onFail(msg);
            }
        });
    }

    public String getWxAppId() {
        return APPID_WX;
    }

    public String getWxSecert() {
        return APP_SECERT_WX;
    }

    public void onHandleIntent(Intent intent, IWXAPIEventHandler iwxapiEventHandler) {
        if (mIwxapi != null)
            mIwxapi.handleIntent(intent, iwxapiEventHandler);
    }

    /**
     * --------------------------------------  WX分享  -------------------------------------------
     */


    public void shareCirHtml(Context ctx, String title, String describe, String url,String urll) {
        shareHtml(ctx, title, describe, url,urll,SCENE_TIMELINE);
    }

    public void shareFriHtml(Context ctx, String title, String describe, String url,String urll) {
        shareHtml(ctx, title, describe, url,urll, SCENE_SESSION);
    }


//    public void shareFri




   //从网络获取图片并转化为bitmap图片
    public static Bitmap getBitMBitmap(Context ctx,String urlpath) {
        Bitmap map = null;
        try {
            URL url = new URL(urlpath);
            URLConnection conn = url.openConnection();
            conn.setReadTimeout(1500);
            conn.setConnectTimeout(1500);
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            map = BitmapFactory.decodeStream(in);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return BitmapFactory.decodeResource(ctx.getResources(), R.drawable.icon);
    }

    private void shareHtml(Context ctx, String title, String describe, String url,String urll, int scene) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;

        if (describe != null) msg.description = describe;

        Bitmap bmp = getBitMBitmap(ctx,urll);
//        Bitmap bmp = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        msg.thumbData = Utils.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = scene;
        boolean flag =   mIwxapi.sendReq(req);
        System.out.println(flag);
    }

    //38e67cf5f82e7ce53102bcf57a20d126
    public static void shareCirMultiPictures(Context ctx, String title, File... files) {
        try {


            Intent intent = new Intent();
            ComponentName comp = new ComponentName("com.tencent.mm",
                    "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.setType("image/*");

            ArrayList<Uri> imageUris = new ArrayList<>();
            for (File f : files) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri uri = insertMediaImage(ctx, f);
                    if (uri != null)
                        imageUris.add(uri);
                } else {
                    imageUris.add(Uri.fromFile(f));
                }
            }
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
            intent.putExtra("Kdescription", title);
            ctx.startActivity(intent);
        } catch (Exception e) {
        }
    }

    public static void shareCirMultiPictures(Context ctx, String title, String... paths) {
        File[] files = new File[paths.length];
        for (int i = 0; i < files.length; i++) {
            files[i] = new File(paths[i]);
        }
        shareCirMultiPictures(ctx, title, files);
    }

    public static void shareCirMultiPictures(Context ctx, String title, List<String> urls) {
        if (urls != null && urls.size() > 0) {
            File[] files = new File[urls.size()];
            for (int i = 0; i < urls.size(); i++) {
                files[i] = new File(urls.get(i));
            }
            shareCirMultiPictures(ctx, title, files);
        }
    }

    private static Uri insertMediaImage(Context ctx, File f) {
        try {
            return Uri.parse(android.provider.MediaStore.Images.Media.insertImage(ctx.getContentResolver(), f.getAbsolutePath(), f.getName(), null));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }






}
